import React, { createContext, useEffect } from 'react'
import ReactDOM from 'react-dom/client'
import './index.css'
import { BrowserRouter, HashRouter, useRoutes } from 'react-router-dom'
import { RouteGuard, routes } from './routes'
import { App, ConfigProvider, theme } from 'antd'
import storage from './storage'
import zhCN from 'antd/locale/zh_CN'
import dayjs from 'dayjs';
import axios from 'axios'
dayjs.locale('zh');
export const Global = createContext();
axios.defaults.withCredentials = true;
axios.interceptors.response.use(
  resp => {
    if (resp.status === 200) {
      return resp.data
    } else if (resp.status === 401) {
      storage.saveUser({ ...storage.getUser(), logined: false });
      return resp
    } else {
      return resp
    }
  }
)
ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <HashRouter>
      <MyApp />
    </HashRouter>
  </React.StrictMode>,
)


function MyApp() {
  let user = storage.getUser();
  const role = user == null ? 0 : user.role == null ? 0 : user.role
  const [logined, setLogined] = React.useState(user && user.logined)
  let a = useRoutes(routes)
  return <>
    <Global.Provider value={{ logined, setLogined, role }}>
      <ConfigProvider locale={zhCN} theme={{
        algorithm: theme.compactAlgorithm,
      }}>
        <App>
          <RouteGuard>
            {a}
          </RouteGuard>
        </App>
      </ConfigProvider>
    </Global.Provider>
  </>
}
